package a.a;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class StreamTutorial extends Activity implements OnClickListener, OnPreparedListener {
    int port;
    MediaPlayer mp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViewById(R.id.play).setOnClickListener(this);
        findViewById(R.id.start).setOnClickListener(this);
    }

    private void startMedia() {
        if (mp != null) {
            mp.release();
            mp = null;
        }
        mp = new MediaPlayer();
        mp.reset();
        try {
            mp.setOnPreparedListener(this);
            Log.d("2", "setDataSource()");
            mp.setDataSource(this, Uri.parse("http://127.0.0.1:" + port + "/"));
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.prepareAsync();
        } catch (Exception e) {
            Log.e("2", "", e);
        }
    }

    private void startStreamService() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = new File(Environment.getExternalStorageDirectory(), "abcde");
                    final FileInputStream in = new FileInputStream(file);
                    ServerSocket socket = new ServerSocket(0);
                    port = socket.getLocalPort();

                    Log.d("2", "waiting...");
                    Socket clientSocket = socket.accept();
                    clientSocket.setKeepAlive(true);
                    OutputStream out = clientSocket.getOutputStream();

                    byte[] buf = new byte[1024];
                    int length;
                    while ((length = in.read(buf)) != -1) {
                        out.write(buf, 0, length);
                        Log.d("2", "write()");
                    }
                    out.flush();

                    in.close();
                    out.close();
                    clientSocket.close();
                } catch (Exception e) {
                    Log.e("2", "", e);
                }
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.start:
            startStreamService();
            break;
        case R.id.play:
            startMedia();
            break;
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.seekTo(0);
        mp.start();
    }
}